package com.lff.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lff.domain.Role;
import com.lff.domain.User;
import com.lff.mapper.RoleMapper;
import com.lff.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 用户登录模块
     *
     * @param userCode
     * @param userPassword
     * @param session
     * @return
     */
    @RequestMapping("login.do")
    public String login(String userCode, String userPassword, HttpSession session) {
        User user = userService.login(userCode, userPassword);
        if (user != null) {
            session.setAttribute("user", user);
            return "frame";
        }
        session.setAttribute("login_error", "用户名或密码错误");
        //设置登陆有效时间 十分钟
        session.setMaxInactiveInterval(600);
        return "redirect:/login.jsp";
    }

    /**
     * 检查原密码是否正确
     *
     * @param oldpassword
     * @param session
     * @return
     */
    @RequestMapping("check.do")
    @ResponseBody
    public String changePwd(String oldpassword, HttpSession session) {
        //用于检查老密码是否正确
        //获取用户id
        User user = (User) session.getAttribute("user");
        if (user != null) {
            if (oldpassword.equals("") || oldpassword == null) {
                //用户没有输入密码
                return "{\"result\":\"error\"}";
            }
            Long id = user.getId();
            if (userService.checkPwd(id, oldpassword) != null) {
                //查询到了user正确 返回正确信息
                return "{\"result\":\"true\"}";
            } else {
                //没有查询到user
                return "{\"result\":\"false\"}";
            }
        } else {
            // 用户登录凭证过期
            return "{\"result\":\"sessionerror\"}";
        }
    }

    /**
     * 密码修改模块
     *
     * @param session
     * @param newpassword
     * @return
     */
    @RequestMapping("changePwd.do")
    @Transactional
    public String changePwd(HttpSession session, String newpassword) {
        //获取当前登录用户id
        User user = (User) session.getAttribute("user");
        Long id = user.getId();
        userService.updatePassword(id, newpassword);
        return "redirect:/login.jsp";
    }

    /**
     * 显示用户列表
     */
//    http://localhost:8080/smbms/user/showUser.do?method=query&queryname=&queryUserRole=0&pageIndex=1
    @RequestMapping("showUser.do")
    public ModelAndView showUser(ModelAndView modelAndView, @RequestParam(value = "pageIndex", defaultValue = "1") Integer startPage, HttpServletRequest request) {
        //获取查询的用户名和用户角色编号
        String queryname = request.getParameter("queryname");
        String strQueryUserRole = request.getParameter("queryUserRole");
        Integer queryUserRole;
        if (strQueryUserRole != null) {
            queryUserRole = Integer.valueOf(strQueryUserRole);
        } else {
            queryUserRole = null;
        }
        //设置分页信息
        PageHelper.startPage(startPage, 5);
        //获取分页数据
        List<User> userList = userService.findAll(queryname, queryUserRole);
        //设置年龄
        Long today = new Date().getTime();
        for (User user : userList) {
            Long difference = today - user.getBirthday().getTime();
            Long year = (1000l * 60l * 60l * 24l * 365l);
            int age = (int) (difference / year);
            if (age == 0) {
                age = 1;
            }
            user.setAge(age);
        }
        //获取分页的其他信息
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        //获取用户角色信息
        List<Role> roleList = roleMapper.findRoleAll();
        //设置视图
        modelAndView.setViewName("userlist");
        //填充数据
        modelAndView.addObject("userList", userList);
        modelAndView.addObject("pageInfo", pageInfo);
        modelAndView.addObject("roleList", roleList);
        //填充用于回显的数据
        modelAndView.addObject("queryname", queryname);
        modelAndView.addObject("queryUserRole", queryUserRole);
        //返回视图
        return modelAndView;
    }

    //退出登录模块
    @RequestMapping("logout.do")
    public String logout(HttpSession session) {
        //清除登录session
        session.invalidate();
        return "../login";
    }

    @RequestMapping("view.do")
    public String showUser(Model model, Integer uid) {
        User user = userService.findById(uid);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(user.getBirthday());
        model.addAttribute("userShow", user);
        model.addAttribute("birthday", format);
        return "userview";
    }

    // 显示修改页面

    @RequestMapping("update")
    public String updateUser(Integer uid, Model model) {
        User user = userService.findById(uid);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(user.getBirthday());
        List<Role> roleList = roleMapper.findRoleAll();
        model.addAttribute("user", user);
        model.addAttribute("roleList", roleList);
        model.addAttribute("birthday", format);
        return "usermodify";
    }

    //修改执行
    @Transactional
    @RequestMapping("update.do")
    public String doUpdateUser(HttpServletRequest request, Model model) throws ParseException {
        User user = new User();
        try {
            user.setId(Long.valueOf(request.getParameter("uid")));
        } catch (NumberFormatException e) {
            return "redirect:showUser.do";
        }
        user.setUserName((String) request.getParameter("userName"));
        String gender = request.getParameter("gender");
        System.err.println(gender);
        Integer integer = Integer.valueOf(gender);
        user.setGender(integer);
        String birthday = request.getParameter("birthday");
        Date parse = new SimpleDateFormat("yyyy-HH-dd").parse(birthday);
        user.setBirthday(parse);
        user.setPhone((String) request.getParameter("phone"));
        user.setAddress((String) request.getParameter("address"));
        Long rid = Long.valueOf(request.getParameter("userRole"));
        Role role = new Role();
        role.setId(rid);
        user.setUserRole(role);
        userService.updateUser(user);
        System.out.println(user);
        //页面回显
        return showUser(model, user.getId().intValue());
    }

    /**
     * 用户删除模块
     *
     * @param id
     * @return
     * @throws JsonProcessingException
     */
    @Transactional
    @RequestMapping("delete.do")
    @ResponseBody//将数据直接回写给页面
    public String delete(@RequestParam("uid") Long id) throws JsonProcessingException {
        Integer result = userService.deleteById(id);
        String delResult = null;
        try {
            if (result == 0) {
                delResult = "notexist";
            } else {
                delResult = "true";
            }
        } catch (Exception e) {
            delResult = "false";
            return "{\"delResult\":\"" + delResult + "\"}";
        }
        return "{\"delResult\":\"" + delResult + "\"}";
    }


    /*--------------------添加用户------------------*/
    //检验userCode是否可用
    @RequestMapping("/checkUserCode.do")
    @ResponseBody //直接返回字符串
    public String queryUserCode(@RequestParam("userCode") String userCode) {
        User user = userService.queryUserCode(userCode);
        if(user == null){
            //不存在
            return "{\"userCode\":\"notExist\"}";
        }
        //存在
        return "{\"userCode\":\"exist\"}";
    }
    //添加操作

    @RequestMapping("/addUser.do")
    @Transactional
    public String addUser(User user,HttpSession session){
        User createUser = (User)session.getAttribute("user");
        //设置创建者信息
        user.setCreatedBy(createUser.getId());
        //设置创建时间
        user.setCreationDate(new Date());
        userService.addUser(user);
        return "redirect:showUser.do";
    }


}
